function formatTime(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();

  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();

  return (
    [year, month, day].map(formatNumber).join("-") +
    " " + [hour, minute, second].map(formatNumber).join(":")
  );
}

function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : "0" + n;
}

function showAlert(n) {
  wx.showAlert();
}

// Uint8Array转字符串

function Uint8ArrayToString(fileData) {
  var dataString = "";
  for (var i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i]);
  }

  return dataString;
}
// 字符串转Uint8Array

function stringToUint8Array(str) {
  var arr = [];
  for (var i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
  var tmpUint8Array = new Uint8Array(arr);
  return tmpUint8Array;
}
//  int转byte[]
function intToBytes2(n) {
  var bytes = [];
  var i = 0;
  do {
    bytes[i++] = n & (255);
    n = n >> 8;
  } while (i < 2)
  return bytes;
  /**
   var bytes=[]
   var i=length
   do{
     bytes[--i]=number&(255)
     number=nubmer>>8;

   }while(i)
   return bytes;
   
   */
}
/**
 * 将int数值转换为占四个字节的byte数组，本方法适用于(低位在前，高位在后)的顺序。 和bytesToInt（）配套使用
 * @param value
 *            要转换的int值
 * @return byte数组
 */
function intToBytes(value) {
  var src = [];
  src[3] = ((value >> 24) & 0xff);
  src[2] = ((value >> 16) & 0xff);
  src[1] = ((value >> 8) & 0xff);
  src[0] = (value & 0xff);
  return src;
}
/**
 * 将int数值转换为占四个字节的byte数组，本方法适用于(高位在前，低位在后)的顺序。  和bytesToInt2（）配套使用
 */
function intToBytes4(value) {
  var src = [];
  src[0] = ((value >> 24) & 0xff);
  src[1] = ((value >> 16) & 0xff);
  src[2] = ((value >> 8) & 0xff);
  src[3] = (value & 0xff);
  return src;
}
/**
 * byte数组中取int数值，本方法适用于(低位在前，高位在后)的顺序，和和intToBytes（）配套使用
 *
 * @param src
 *            byte数组
 * @param offset
 *            从数组的第offset位开始
 * @return int数值
 */
function bytesToInt(src, offset) {
  var value;
  value = int(
    (src[offset] & 0xff) |
    ((src[offset + 1] & 0xff) << 8) |
    ((src[offset + 2] & 0xff) << 16) |
    ((src[offset + 3] & 0xff) << 24)
  );
  return value;
}

/**
 * byte数组中取int数值，本方法适用于(低位在后，高位在前)的顺序。和intToBytes2（）配套使用
 */
function bytesToInt2(src, offset) {
  var value;
  value = int(
    ((src[offset] & 0xff) << 24) |
    ((src[offset + 1] & 0xff) << 16) |
    ((src[offset + 2] & 0xff) << 8) |
    (src[offset + 3] & 0xff)
  );
  return value;
}

//string转ArrayBuffer

function str2ab(str) {
  var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
  var bufView = new Uint16Array(buf);
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}
//ArrayBuffer转String
function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}

function arrayBufferToHexString(buffer) {
  let bufferType = Object.prototype.toString.call(buffer);
  if (buffer != "[object ArrayBuffer]") {
    return;
  }
  let dataView = new DataView(buffer);

  var hexStr = "";
  for (var i = 0; i < dataView.byteLength; i++) {
    var str = dataView.getUint8(i);
    var hex = (str & 0xff).toString(16);
    hex = hex.length === 1 ? "0" + hex : hex;
    hexStr += hex;
  }

  return hexStr.toUpperCase();
}

function hexStringToArrayBuffer(str) {
  if (!str) {
    return new ArrayBuffer(0);
  }

  var buffer = new ArrayBuffer(str.length);
  let dataView = new DataView(buffer);

  let ind = 0;
  for (var i = 0, len = str.length; i < len; i += 2) {
    let code = parseInt(str.substr(i, 2), 16);
    dataView.setUint8(ind, code);
    ind++;
  }

  return buffer;
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
    return ("00" + bit.toString(16)).slice(-2);
  });
  return hexArr.join("");
}

// 16进制字符串转ArrayBuffer
function hex2ab(value) {
  var typedArray = new Uint8Array(
    value.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16);
    })
  );
  var buffer = typedArray.buffer;
  var bufLen = buffer.byteLength;
  if (Math.floor(bufLen % 20) != 0) {
    var fillBuffer = new Uint8Array(Math.ceil(bufLen / 20) * 20);
    fillBuffer.set(typedArray);
    buffer = fillBuffer.buffer;
  }
  return buffer;
}

/**
 * 字符串转16进制(只支持16进制的字符串)
 */
function strToHexCharCode(str) {
  if (str === "") return "";
  var hexCharCode = [];
  for (var i = 0; i < str.length; i++) {
    hexCharCode.push(str.charCodeAt(i).toString(16));
  }
  return hexCharCode.join("");
}

// 异或
function XOR(b, len) {
  var tmp = b[0];
  for (var i = 1; i < len; i++) {
    tmp ^= b[i];
  }
  return tmp;
}

// byte[]转整形
function bytesToLong(bytValue) {
  var ret = 0;
  for (var i = 0; i < bytValue.length; i++) {
    ret += (bytValue[i] & 0xFF) << (i * 4);
  }
  return ret;
}

/**
 * 十六进制转字符串
 */
function hexCharCodeToStr(hexCharCodeStr) {
  var trimedStr = hexCharCodeStr.trim();
  var rawStr = trimedStr;
  var len = rawStr.length;
  if (len % 2 !== 0) {
    console.log("Illegal Format ASCII Code!");
    return "";
  }
  var curCharCode;
  var resultStr = [];
  for (var i = 0; i < len; i = i + 2) {
    curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value

    resultStr.push(String.fromCharCode(curCharCode));
  }
  return resultStr.join("");
}
/**
 * byte[] 数组转十六进制字符串 带空格的
 */
function byteArrayToHexBankStr(arrayValue) {
  var hexStr = "";
  for (var arrayItem of arrayValue) {
    var charHex = arrayItem.toString(16);
    charHex = Math.floor(charHex.length % 2) == 0 ? charHex : `0${charHex}`;
    charHex = charHex + " ";
    hexStr = `${hexStr}${charHex}`;
  }
  return hexStr.toLocaleUpperCase().trim();
}
/**
 *byte[] 数组转十六进制字符串
 * @param strValue byte[] 数组
 * @returns {string}
 */
function byteArrayToHex(arrayValue) {
  var hexStr = "";
  if (!arrayValue) {
    return hexStr;
  }
  for (let i = 0; i < arrayValue.length; i++) {
    var charHex = arrayValue[i].toString(16);
    charHex = Math.floor(charHex.length % 2) == 0 ? charHex : `0${charHex}`;
    hexStr = `${hexStr}${charHex}`;
  }
  return hexStr.toLocaleUpperCase();
}

/**
 * array to arrayBuffer
 */
function byteArrayToArrayBuffer(arrayValue) {
  var hexStr = byteArrayToHex(arrayValue);
  var arryBuffer = hex2ab(hexStr);
  return arryBuffer;
}

/**
 * 十六进制字符串转byte[]
 * @param hexStrValue 十六进制字符串
 *
 */
function hexStrToByte(hexStrValue) {
  var hexValueLen = hexStrValue.length;
  var arrayCode = [];
  if (Math.floor(hexValueLen % 2) != 0) {
    hexStrValue = `${hexStrValue}0`;
  }
  for (var i = 0; i < hexValueLen; i += 2) {
    var itemValue = hexStrValue.substring(i, i + 2);
    arrayCode.push(parseInt(itemValue, 16));
  }
  return arrayCode;
}

/**
 * byte[] 转字符串
 * @param byteArrayValue 数组
 * @returns {string}
 */
function byteArrayToStr(byteArrayValue) {
  var str = "";
  for (var arrayItem of byteArrayValue) {
    str = `${str}${String.fromCharCode(arrayItem)}`;
  }
  return str;
}

/**
 * 字符串转byte[]
 * @param strValue ASCII字符串
 * @returns {Array}数组
 */
function strToIntArray(strValue) {
  var intAray = [];
  var valueLen = strValue.length;
  for (var i = 0; i < valueLen; i++) {
    intAray.push(strValue.charCodeAt(i));
  }
  return intAray;
}
//sleep time
function sleepTime(millsecond) {
  var nowTime = new Date();
  var expeir = nowTime.getTime() + millsecond;
  while (true) {
    nowTime = new Date();
    if (nowTime.getTime() > expeir) {
      return true;
    }
  }
}
//对象深复制
function objDeepCopy(source) {
  var sourceCopy = {};
  for (var item in source) {
    sourceCopy[item] =
      typeof source[item] === "object" ?
      objDeepCopy(source[item]) :
      source[item];
  }
  return sourceCopy;
}
//异或和计算
function chk8xor(byteArray) {
  let checksum = 0x00
  for (let i = 0; i < byteArray.length - 1; i++) {
    checksum ^= byteArray[i]
  }
  return checksum
}
//算术和计算
function calce(byteArray) {
  let checksum = 0x00
  for (let i = 0; i < byteArray.length - 1; i++) {
    checksum += byteArray[i]
  }
  console.log("calce:int " + checksum)
  let hexStr = checksum.toString(radix)
  console.log("calce:hexStr " + hexStr)
  return hexStr
}
//取某一bit位
function fetchOneBit(data, index) {
  return (data & (0x1 << index)) >> index
}
//获取持续的0-7bit位
function fetchSeries7Bit(data) {
  return (data & 0xFE) >> 1
}
//字符串转ascii
function strToAscii(str) {
  return str.charCodeAt()
}
//ascii 转字符串
function AsciiToStr(params) {
  console.log(params,String.fromCharCode(params));
  return String.fromCharCode(params);
}

module.exports = {
  formatTime: formatTime,
  HexStrToByte: hexStrToByte,
  ByteArrayToHexBankStr: byteArrayToHexBankStr,
  byteArrayToHex: byteArrayToHex,
  sleepTime: sleepTime,
  objDeepCopy: objDeepCopy,
  chk8xor: chk8xor,
  calce: calce,
  intToBytes: intToBytes,
  fetchOneBit: fetchOneBit,
  fetchSeries7Bit: fetchSeries7Bit,
  intToBytes2: intToBytes2,
  intToBytes4: intToBytes4,
  ab2hex: ab2hex,
  hex2ab: hex2ab,
  bytesToLong: bytesToLong,
  hexCharCodeToStr:hexCharCodeToStr
};